import { defineComponent, PropType, useAttrs } from 'vue';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import type { MenuItem } from './interface';

export default defineComponent({
  props: {
    data: {
      type: Array as PropType<MenuItem[]>,
      require: true,
      default: () => [],
    },
    defaultActive: {
      type: String,
      default: ' ',
    },
    router: {
      type: Boolean,
      default: false,
    },
  },

  setup(props) {
    const renderMenu = (meunItem: MenuItem[]) => {
      return meunItem.map((item: MenuItem) => {
        const icon = item.icon ? (ElementPlusIconsVue as SafeAny)[item.icon] : '';
        const slots = {
          title: () => {
            return icon ? (
              <>
                <icon />
                <span>{item.name}</span>
              </>
            ) : (
              <>
                <span>{item.name}</span>
              </>
            );
          },
        };

        if (item.children && item.children.length) {
          return (
            <el-sub-menu v-slots={slots} index={item.index}>
              {renderMenu(item.children)}
            </el-sub-menu>
          );
        }

        return (
          <el-menu-item index={item.index}>
            <icon />
            <span>{item.name}</span>
          </el-menu-item>
        );
      });
    };
    const attrs = useAttrs();
    return () => {
      return (
        <el-menu default-active={props.defaultActive} router={props.router} {...attrs} class="mn-menu">
          {props.data && renderMenu(props.data)}
        </el-menu>
      );
    };
  },
});
